package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.cons.GeneralTypeEnum;
import cn.stylefeng.guns.core.common.constant.Const;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.exception.NumberErrorException;
import cn.stylefeng.guns.core.common.util.*;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.FileUtil;
import cn.stylefeng.guns.modular.api.HttpClientService;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.model.CarDto;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.modular.system.warpper.AllRentDtoWarpper;
import cn.stylefeng.guns.modular.system.warpper.CarWarpper;
import cn.stylefeng.guns.modular.system.warpper.RentWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.jnlp.FileSaveService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 车辆管理控制器
 *
 * @author LST
 * @Date 2019
 */
@Controller
@RequestMapping("/car")
public class CarController extends BaseController {

    private static String PREFIX = "/system/car/";

    @Autowired
    private CarService carService;

    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private RentService rentService;

    @Autowired
    private ActivityService activityService;
    /**
     * 跳转到查看车辆页面
     *
     */
    @ApiOperation(value = "车辆页面跳转",httpMethod = "GET")
    @RequestMapping("")
    public String index() {
        return PREFIX + "car.html";
    }

    /**
     * 跳转到添加车辆页面
     * @return
     */
    @ApiOperation(value = "车辆增加页面跳转",httpMethod = "GET")
    @RequestMapping("/car_add")
    public String addView() {
        return PREFIX + "car_add.html";
    }

    /**
     * 跳转到更新车辆页面
     *
     */
    @ApiOperation(value = "车辆更新页面跳转",httpMethod = "GET", notes = "需要cardId参数")
    @Permission
    @RequestMapping("/car_edit")
    public String carEdit(@RequestParam Long carId) {
        if (ToolUtil.isEmpty(carId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取信息
        Car car = this.carService.getById(carId);
        //
        LogObjectHolder.me().set(car);
        return PREFIX + "car_edit.html";
    }
    /**
     * 跳转到租车页面
     *
     */
    @ApiOperation(value = "租车页面",httpMethod = "POST", notes = "需要cardId参数")
    @Permission
    @RequestMapping("/car_rent")
    public String carRent(@RequestParam Long carId) {
        if (ToolUtil.isEmpty(carId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取信息
        Car car = this.carService.getById(carId);
        if (ToolUtil.isEmpty(car)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //
        LogObjectHolder.me().set(car.getCarId());
        return "/system/rent/car_rent.html";
    }

    /**
     * 正式租车
     *
     */
    @ApiOperation(value = "正式租车",httpMethod = "POST", notes = "需要carDto参数")
    @Permission
    @ResponseBody
    @RequestMapping("/rent")
    public ResponseData carRent(@Valid CarDto carDto ,BindingResult result) {
        if (ToolUtil.isEmpty(carDto)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //如果租车记录中有这个人租了车，则不能继续租车
        Long aLong = rentService.selectRecord(userId);
        if (!ToolUtil.isEmpty(aLong)) {
            throw new ServiceException(BizExceptionEnum.YOU_HAS_RENT);
        }
        Long carId = carDto.getCarId();
        if (ToolUtil.isEmpty(carDto.getCarId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Date now = new Date();
        Date returnDate = carDto.getReturnDate();
        Long difference = DateUtil.getDifference(returnDate, now);
        if (difference <= 0) throw new NumberErrorException();
        BankCard bankCard = httpClientService.lookCard(userId);
        if (ToolUtil.isEmpty(bankCard)) {
            throw new ServiceException(BizExceptionEnum.NO_BANKCARD);
        }
        Car car = carService.getById(carId);

        if (ToolUtil.isEmpty(car)) car.setRentTimes(GeneralTypeEnum.DEFAULT_TIMES.getCode());
        car.setRentTimes(car.getRentTimes() + GeneralTypeEnum.RENT_TIMES.getCode() );
        car.setIsRent(GeneralTypeEnum.IS_RENT.getCode());
        carService.updateById(car);
        Double moneyDifference = MoneyDifference.getMoneyDifference(bankCard.getCardMoney(), carDto.getRentMoneyOneDay(), difference);
        Rent rent = PackageObject.packageRent(userId, carId, bankCard.getCardName(), car.getCarType(), now, moneyDifference);
        rentService.save(rent);
        rentService.insertRecord(userId,carId);
        return SUCCESS_TIP;
    }

    /**
     * 还车
     */
    @ApiOperation(value = "还车",httpMethod = "POST", notes = "不需要参数，但是用户需要有数据")
    @RequestMapping("/return")
    @ResponseBody
    public ResponseData renturnCar() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        BankCard bankCard = httpClientService.lookCard(userId);
        Long carId = rentService.selectRecord(userId); //获取租车记录
        Car car = carService.getById(carId);
        Long mileage = httpClientService.getThisCarMileage();
        car.setCarMileage(car.getCarMileage() + mileage);  //更新里程  里程使接口中随机生成的数据，用于模仿汽车里程表
        car.setIsRent(GeneralTypeEnum.NO_RENT.getCode());
        Rent rent = rentService.selectRent(userId);
        Date now = new Date();
        Long difference = DateUtil.getDifference(now, rent.getRentTime());
        if (difference == 0) difference = 1L; //如果归还时间小于一天 按一天算
        //加上折扣信息
        //先更新是否过期
        List<Map<String, Object>> activitys = null;
        activitys = activityService.selectActivitys(null, null);
        //检测时间 如果过期就修改为已经过期
        Date today = new Date();
        if (activitys.size() > 0){
            for (Map<String, Object> activity : activitys) {
                Date old = (Date)activity.get("endTime");
                if (DateUtil.getDifference(old, today) < 0){
                    Activity thisClass = JSONObject.parseObject(JSONObject.toJSONString(activity), Activity.class);
                    thisClass.setIsTimeout(GeneralTypeEnum.IS_TIMEOUT.getCode());
                    activityService.updateById(thisClass);
                }
            }
        }
        List<Long> activityIds = activityService.selectActivityId(userId);
        //查询出来该用户拥有的折扣信息（未过期）
        if (activityIds.size() != 0){
            activitys = activityService.selectDiscount(activityIds);
        }
        //如果有折扣信息
        Double money = null;
        if (activitys.size() == 0){
            money = MoneyDifference.getRentMoney(car.getRentMoneyOneDay().doubleValue(), difference); //租车金额
        }else {
            money = MoneyDifference.getRentMoneyHasActivity(car.getRentMoneyOneDay().doubleValue(), difference , activitys); //租车金额
        }
        Double howMoney = MoneyDifference.getDifference(bankCard.getCardMoney(), money);
        if (howMoney <= 0) new ServiceException(BizExceptionEnum.MONEY_CAN_NOT_RETURN);
        carService.updateById(car);//更新车辆信息，===没有被租赁
        rent.setRentMoney(money);
        rent.setReTime(now);
        rent.setIsReturn(GeneralTypeEnum.IS_RETURN.getCode());
        rentService.updateById(rent);//更新租车详情，归还时间
        rentService.deleteRecord(userId); //删除租车记录
        bankCard.setCardMoney(howMoney);//修改金额，直接用银行卡余额减去金额
        httpClientService.editCard(bankCard); //更新银行卡信息
        return SUCCESS_TIP;
    }
    /**
     * 租车可买断
     */
    @ApiOperation(value = "租车买断",httpMethod = "GET", notes = "用户需要租赁过这辆车否则不可以")
    @RequestMapping("/buy")
    @ResponseBody
    public ResponseData buy() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        BankCard bankCard = httpClientService.lookCard(userId);
        Long carId = rentService.selectRecord(userId); //获取租车记录
        if (carId == null ||carId == 0 ) {
            throw new ServiceException(BizExceptionEnum.NO_BUY_PERMISSION);
        }
        Car car = carService.getById(carId); //获取这个车辆的信息

        Rent rent = rentService.selectRent(userId); //获取租赁信息用于更新是否还车字段

        Double carPrice = car.getCarPrice(); //车辆价值

        Double cardMoney = bankCard.getCardMoney(); //银行卡余额

        Double difference = MoneyDifference.getDifference(cardMoney, carPrice); //车辆价值-银行卡余额

        if (difference <= 0) new ServiceException(BizExceptionEnum.MONEY_NOT_ENOUGH);
        carService.removeById(car.getCarId()); //删除此车辆信息
        rent.setIsReturn(GeneralTypeEnum.IS_RETURN.getCode());
        rentService.updateById(rent);   //更新车辆租车信息 保证下次搜索搜索不到这辆车的租车信息
        rentService.deleteRecord(userId); //删除租车记录
        //获取预约记录  如果预约记录大于0  则删除这条预约记录
        List<Long> carIds = carService.getMyOrderCar(userId);
        if (carIds.size() != 0){
            car.setIsOrder(GeneralTypeEnum.NO_ORDER.getCode());
            carService.deleteThisOrder(userId);
        }
        bankCard.setCardMoney(difference);  //修改金额，直接用银行卡余额减去金额
        httpClientService.editCard(bankCard); //更新银行卡信息
        return SUCCESS_TIP;
    }

    /**
     * 通过id收藏车辆
     *
     */
    @ApiOperation(value = "通过id收藏",httpMethod = "POST", notes = "需要参数cardId")
    @Permission
    @ResponseBody
    @RequestMapping("/car_collection")
    public ResponseData carCollection(@RequestParam Long carId) {
        if (ToolUtil.isEmpty(carId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取信息
        Car car = this.carService.getById(carId);
        if (ToolUtil.isEmpty(car)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        CollectionCar collectionCar = new CollectionCar();
        collectionCar.setUserId(userId);
        collectionCar.setCarId(carId);
        carService.insertCollectionCar(collectionCar);
        return SUCCESS_TIP;
    }
    /**
     * 跳转到我的收藏
     *
     */
    @ApiOperation(value = "收藏页面跳转",httpMethod = "GET", notes = "需要参数cardId")
    @Permission
    @RequestMapping("/myCollection")
    public String collection() {
        return PREFIX + "my_collection_car.html";
    }

    /**
     * 查询我的收藏列表
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "默认数据获取",httpMethod = "GET")
    @RequestMapping("/myCollectionCar")
    @Permission
    @ResponseBody
    public Object myCollectionCar() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> carIds = carService.getMyCollectionCar(userId);
        if (carIds.size() == 0){
            return null;
        }
        List<Map<String, Object>> cars = carService.selectCollectionCars(carIds);
        return new CarWarpper(cars).wrap();
    }

    /**
     * 通过id预约车辆
     *
     */
    @ApiOperation(value = "车辆预约",httpMethod = "POST", notes = "需要参数cardId")
    @Permission
    @ResponseBody
    @RequestMapping("/car_order")
    public ResponseData carOrder(@RequestParam Long carId) {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> carIds = carService.getMyOrderCar(userId);
        if (carIds.size() >= 1){
            throw new ServiceException(BizExceptionEnum.ORDER_IS_ON);
        }
        if (ToolUtil.isEmpty(carId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取信息
        Car car = this.carService.getById(carId);
        car.setIsOrder(GeneralTypeEnum.IS_ORDER.getCode());
        this.carService.updateById(car);
        if (ToolUtil.isEmpty(car)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        OrderCar orderCar = new OrderCar();
        orderCar.setUserId(userId);
        orderCar.setCarId(carId);
        carService.insertOrderCar(orderCar);
        return SUCCESS_TIP;
    }

    /**
     * 跳转到我的预约
     *
     */
    @ApiOperation(value = "预约跳转",httpMethod = "GET")
    @Permission
    @RequestMapping("/myOrder")
    public String myOrder() {
        return PREFIX + "my_order_car.html";
    }
    /**
     * 查询我的预约列表
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "我的预约车辆",httpMethod = "GET")
    @RequestMapping("/myOrderCar")
    @Permission
    @ResponseBody
    public Object myOrderCar() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> carIds = carService.getMyOrderCar(userId);
        if (carIds.size() == 0){
            return null;
        }
        List<Map<String, Object>> cars = carService.selectOrderCar(carIds);
        return new CarWarpper(cars).wrap();
    }

    /**
     * 取消我的预约
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "取消预约",httpMethod = "GET")
    @RequestMapping("/cancelOrder")
    @Permission
    @ResponseBody
    public ResponseData cancelOrder() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> carIds = carService.getMyOrderCar(userId);
        if (carIds.size() == 0){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Car car = carService.getById(carIds.get(0));
        car.setIsOrder(GeneralTypeEnum.NO_ORDER.getCode());
        carService.updateById(car);
        carService.deleteThisOrder(userId);
        return SUCCESS_TIP;
    }

    /**
     * 查询车辆列表
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "车辆表获取",httpMethod = "GET", notes = "需要参数cardType,carColor")
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String carType,
                       @RequestParam(required = false) String carColor) {
            List<Map<String, Object>> cars = carService.selectCars(carType, carColor);
            return new CarWarpper(cars).wrap();
    }

    @RequestMapping("/myRent")
    public String myRent(){
        return "/system/rent/rent.html";
    }
    /**
     * 查询我的租车信息
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "获取租车表",httpMethod = "GET")
    @RequestMapping("/rentList")
    @ResponseBody
    public Object rentList() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Map<String, Object>> rents = rentService.selectRents(userId);
        return new RentWarpper(rents).wrap();
    }

    /**
     * 添加车辆
     *
     * @author fengshuonan
     */
    @RequestMapping("/add")
    @Permission
    @ResponseBody
    public ResponseData add(@Valid Car car, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        car.setIsRent(GeneralTypeEnum.NO_RENT.getCode());
        car.setIsOrder(GeneralTypeEnum.NO_ORDER.getCode());
        car.setIsDel(GeneralTypeEnum.NO_DELETE.getCode());
        this.carService.addCar(car);
        return SUCCESS_TIP;
    }

    /**
     * 更新车辆信息
     * @author fengshuonan
     */
    @ApiOperation(value = "更新车辆信息",httpMethod = "POST", notes = "需要参数car")
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseData edit(@Valid Car car, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.carService.editCar(car);
        return SUCCESS_TIP;
    }

    /**
     * 删除车辆（逻辑删除）
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "删除车辆信息",httpMethod = "POST", notes = "需要参数carId")
    @RequestMapping("/delete")
    @Permission
    @ResponseBody
    public ResponseData delete(@RequestParam Long carId) {
        if (ToolUtil.isEmpty(carId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.carService.deleteCar(carId);
        return SUCCESS_TIP;
    }

    /**
     * 获取车辆详情
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "默认车辆获取，回调专用",httpMethod = "GET", notes = "需要参数carId")
    @RequestMapping("/getCarInfo")
    @ResponseBody
    public Object getCarInfo(@RequestParam Long carId) {
        if (ToolUtil.isEmpty(carId)) {
            throw new RequestEmptyException();
        }
        Car car = carService.getById(carId);
        return ResponseData.success(car);
    }
    /**
     * 获取带有归还时间的车辆详情
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "设置归还时间回调",httpMethod = "GET", notes = "需要参数carId")
    @RequestMapping("/getCarInfoHasReturn")
    @ResponseBody
    public Object getCarInfoHasReturn(@RequestParam Long carId) throws IllegalAccessException, ClassNotFoundException {
        if (ToolUtil.isEmpty(carId)) {
            throw new RequestEmptyException();
        }
        Car car = carService.getById(carId);
        CarDto carDto = new CarDto();
        //将两个对象中相同属性名的值copy，源对象---->目标对象
        BeanUtils.copyProperties(car,carDto);
        /*List<Map<String, Object>> maps = ObjectUtil.compareTwoClass(car, carDto);*/
        return ResponseData.success(carDto);
    }

    /**
     * poi导出
     *
     * @author fengshuonan
     */
    @ApiOperation(value = "poi导出我的车辆信息表",httpMethod = "GET")
    @RequestMapping("/getMyRentEls")
    public void getMyRentEls(HttpServletResponse response) throws IOException {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Map<String, Object>> rents = rentService.selectRents(userId);
        String fileName = "我的租车信息";
        response.setContentType("application/excel"); //响应类型
        response.setHeader("Content-disposition",
                "attachment;filename=" +
                        fileName +";filename*=utf-8''"+
                        URLEncoder.encode(fileName,"UTF-8")); //响应样式 ，URLEncoder防止中文乱码
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("租车信息表"); //创建sheet并且给定表名
        int rowNum=0;
        String[] headers={"姓名","车辆类型","租赁时间","押金","实际支付(元)"}; //第一列中文
        HSSFRow row=sheet.createRow(rowNum); //创建行
        for (int i =0; i <headers.length;i++){
            HSSFCell cell=row.createCell(i);  //通过行创建列
            HSSFRichTextString text=new HSSFRichTextString(headers[i]); //对第一行第一列设置文字或字体
            cell.setCellValue(text);  //创建1行5列成功
        }
        //添加数据
        for (Map<String, Object> rent : rents) {
            rowNum++;
            HSSFRow row1=sheet.createRow(rowNum);  //每次创建一行
            row1.createCell(0).setCellValue(rent.get("cardName").toString());
            row1.createCell(1).setCellValue(rent.get("carType").toString());
            row1.createCell(2).setCellValue(rent.get("rentTime").toString());
            row1.createCell(3).setCellValue(rent.get("rentDeposit").toString());
            row1.createCell(4).setCellValue(rent.get("rentMoney").toString());
        }
        workbook.write(response.getOutputStream());
    }

    /**
     * 跳转到评论界面
     * @return
     */
    @ApiOperation(value = "评论页面跳转",httpMethod = "POST", notes = "需要参数recordId")
    @RequestMapping("/car_assess")
    public String carAssess(@RequestParam Long recordId){
        if (ToolUtil.isEmpty(recordId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取信息
        Rent rent = this.rentService.getById(recordId);
        //
        LogObjectHolder.me().set(rent);
        return "/system/rent/assess.html";
    }

    /**
     * 评论
     * @return
     */
    @ApiOperation(value = "得到评论",httpMethod = "POST", notes = "需要参数recordId,rentAssess,carScore")
    @RequestMapping("/assess")
    @ResponseBody
    public ResponseData assess(@RequestParam Long recordId,
                               @RequestParam String rentAssess,
                               @RequestParam String carScore){
        Float score = Float.valueOf(carScore);
        StringBuilder sb = new StringBuilder();
        String assess = null;
        //获取信息
        Rent rent = rentService.getById(recordId);
        if (!ToolUtil.isEmpty(rentAssess)){
            assess = ObjectUtil.toSplit(rentAssess); //字符串去空格
        }
        if (!ToolUtil.isEmpty(rent.getRentAssess())){
            assess = rent.getRentAssess() + "%" +assess;
        }
        rent.setRentAssess(assess);
        rentService.updateById(rent);
        Car car = carService.getById(rent.getCarId());
        if (!ToolUtil.isEmpty(car.getCarScore())){ //如果不是空的就计算一下评分 取最低分
            score = MoneyDifference.getFloatDifference(car.getCarScore(), score);
        }
        car.setCarScore(score);

        carService.updateById(car);

        return SUCCESS_TIP;
    }


    /**
     * 查看所有评论页面跳转
     */
    @ApiOperation(value = "评论页面跳转",httpMethod = "GET", notes = "需要参数carId")
    @RequestMapping("/seeAssess")
    public String seeAssess(@RequestParam Long carId){
        Car car = carService.getById(carId);
        LogObjectHolder.me().set(car);
        return "/system/car/car_assess.html";
    }

    @Autowired
    private UserService userService;
    /**
     * 查看所有评论
     * @return
     */
    @ApiOperation(value = "查看所有评论",httpMethod = "GET", notes = "需要参数carId")
    @RequestMapping("/see")
    @ResponseBody
    public Object see(@RequestParam Long carId){
        if (ToolUtil.isEmpty(carId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //获取当前用户
        User user = userService.getById(userId);
        //获取关于这辆车的所有的租车信息表
        List<Map<String, Object>> rents = rentService.selectRentsByCar(carId);
        if (rents.size() == 0){
            throw new ServiceException(BizExceptionEnum.THE_CAR_NO_RENT);
        }
        //获取这辆车的信息
        Car car = carService.getById(carId);
        List<Map<String, Object>> allrents = null;
        try {
            allrents = ObjectUtil.getListNoteToObject(rents,car);
        } catch (IllegalAccessException e) {
            throw new ServiceException(BizExceptionEnum.THE_CAR_NO_RENT);
        }
        return new AllRentDtoWarpper(allrents).wrap();
    }


    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 上传图片链接跳转
     */

    @RequestMapping("/car_file")
    public String carFile(){
        return PREFIX + "car_view.html";
    }

    /**
     * 上传车辆图片
     * @return
     */
    @ApiOperation(value = "上传图片",notes = "carImg(base64),carId")
    @PostMapping("/uploadCarImg")
    @ResponseBody
    public Object uploadCarImg(@RequestParam MultipartFile file,
                               @RequestParam(required = false) String carId,
                               HttpServletRequest request){
        if (ToolUtil.isEmpty(file)) {
            throw new RequestEmptyException("请求图片为空");
        }
        if (ToolUtil.isEmpty(carId)) {
            throw new RequestEmptyException("请选择车辆再上传");
        }

        //获取项目绝对路径
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String webappRoot = classpath.replaceAll("target/classes/", "");


        if (ToolUtil.isEmpty(carId)) {
            throw new RequestEmptyException("没有此车记录，请重新选择");
        }
        String filePath = FileUtil.saveImage(file, webappRoot, request);
        Car car = carService.getById(Long.valueOf(carId));
        car.setCarImg(filePath);   //将路径存入数据库
        boolean b = carService.updateById(car);
        return SUCCESS_TIP;
    }



    @ApiOperation(value = "controller测试",httpMethod = "GET")
    @RequestMapping("/addCar")
    @ResponseBody
    public Boolean addCar(){
        Car car = new Car();
        car.setCarColor("111");
        car.setCarInspection(1);
        car.setCarMileage(new Long(121231212));
        car.setRentTimes(1);
        car.setCarColor("111");
        boolean b = carService.saveOrUpdate(car);
        System.out.println(b + "----------------------");
        return b;
    }
}
